package com.eol.service.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.eol.common.config.SystemPropertiesConfig;
import com.eol.common.exception.BaseException;
import com.eol.entity.dto.wx.WechatUserAuthDto;
import com.eol.entity.dto.wx.WechatUserInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * WxMpService
 *
 * @author liulinhui
 * @email 1249055292@qq.com
 * @date 2020/6/1 22:33
 */
@Service
@Slf4j
public class WechatMpService {

    @Resource
    private RestTemplate restTemplate;
    @Resource
    private SystemPropertiesConfig systemPropertiesConfig;


    /**
     * 通过code获取用户的access_token
     *
     * @param code code
     * @return accessToken
     */
    public WechatUserAuthDto getAccessTokenByCode(String code) {
        String url = String.format("https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code",
                systemPropertiesConfig.getWxMp().getAppId(), systemPropertiesConfig.getWxMp().getAppSecret(), code);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        JSONObject body = (JSONObject) JSON.parse(responseEntity.getBody());
        if (null == body) {
            throw new BaseException("微信对接失败");
        }
        log.info("微信登录对接返回:{}", body.toJSONString());
        return body.toJavaObject(WechatUserAuthDto.class);
    }

    public WechatUserInfoDto oauth2getUserInfo(String openId, String token) {
        String url = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=%s", token, openId, "zh_CN");
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        JSONObject body = (JSONObject) JSON.parse(responseEntity.getBody());
        if (null == body) {
            throw new BaseException("微信对接失败");
        }
        log.info("微信获取用户基本信息对接返回:{}", body.toJSONString());
        return body.toJavaObject(WechatUserInfoDto.class);
    }

}
